﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

public class ScreensManager : Singleton<ScreensManager>
{
	public GameObject canvasPrefab;
	public Camera cameraUI;

	private RectTransform canvas;
	private RectTransform rectTemp;
	private Dictionary<ScreenID, GameObject> spawnedScreens = new Dictionary<ScreenID, GameObject>();
	//private Dictionary<PopupID, GameObject> spawnedPopups = new Dictionary<PopupID, GameObject>();

	private void Awake()
	{
		canvas = ((GameObject)Instantiate(canvasPrefab)).transform as RectTransform;
		canvas.position = Vector3.left * 10f;
		cameraUI = canvas.GetComponentInChildren<Camera>();
		DontDestroyOnLoad(canvas);
		
		PoolManager.Instance.AddToPool(Resources.LoadAll<GameObject>("UI/Screens"));
		PoolManager.Instance.AddToPool(Resources.LoadAll<GameObject>("UI/Popups"));
		PoolManager.Instance.AddToPool(Resources.LoadAll<GameObject>("UI/Panels"));
		PoolManager.Instance.AddToPool(Resources.LoadAll<GameObject>("UI/Widgets"));
		PoolManager.Instance.AddToPool(Resources.LoadAll<GameObject>("UI/Buttons"));
		
		ShowScreen(ScreenID.Screen_HUD);
	}

	public void ShowScreen(ScreenID _screenID)
	{
		GameObject obj = PoolManager.Instance.GetFromPool(_screenID.ToString());
		SetParent(obj, canvas);
		spawnedScreens.Add(_screenID, obj);
	}

	public GameObject ShowPopup(PopupID _popupID)
	{
		GameObject obj = PoolManager.Instance.GetFromPool(_popupID.ToString());

		obj.transform.SetParent(canvas);
		obj.transform.localScale = Vector3.one;
		obj.transform.localPosition = new Vector3(-100, 0, 0);

		//spawnedPopups.Add(_popupID, obj);
		return obj;
	}

	public void RemovePopup(GameObject _popup)
	{
		PoolManager.Instance.ReturnToPool(_popup);
	}
	
	public GameObject GetScreen(ScreenID _screen)
	{
		if (spawnedScreens.ContainsKey(_screen))
		{
			return spawnedScreens[_screen];
		}

		return null;
	}
	
	public void SetParent(GameObject _obj, RectTransform _parent)
	{
		rectTemp = _obj.GetComponent<RectTransform>();
		rectTemp.SetParent(_parent);
		
		rectTemp.anchoredPosition = Vector2.zero;
		rectTemp.anchorMin = Vector2.zero;
		rectTemp.anchorMax = Vector2.one;
		rectTemp.sizeDelta = Vector2.zero;
		rectTemp.localScale = Vector3.one;
	}
	
	public void SetParent(GameObject _obj)
	{
		rectTemp = _obj.GetComponent<RectTransform>();
		rectTemp.SetParent(canvas);
		rectTemp.localScale = Vector3.one;
	}
}
